package com.group.nepm.publicSuperviseDataManagement.controller;

import com.group.common.users.NEPSUser;
import com.group.common.utils.MyUtils;
import com.group.nepm.publicSuperviseDataManagement.entity.AssignData;
import com.group.neps.entity.City;
import com.group.neps.entity.Province;
import com.group.neps.entity.RowAqiData;
import com.group.neps.entity.RowAqiLevel;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.StringConverter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PublicSuperviseDataList {

    @FXML
    private TableView<RowAqiData> tableView;
    @FXML
    private TableColumn<RowAqiData,String> colId;
    @FXML
    private TableColumn<RowAqiData,String> colName;
    @FXML
    private TableColumn<RowAqiData,String> colProvince;
    @FXML
    private TableColumn<RowAqiData,String> colCity;
    @FXML
    private TableColumn<RowAqiData,String> colLevel;
    @FXML
    private TableColumn<RowAqiData,String> colDate;
    @FXML
    private TableColumn<RowAqiData,String> colTime;
    @FXML
    private TableColumn<RowAqiData,Void> colDetail;
    @FXML
    private TableColumn<RowAqiData,Void> colAssign;
    @FXML
    private Button btnCheck;
    @FXML
    private Button btnClear;
    @FXML
    private ComboBox<Province> cobProvince;
    @FXML
    private ComboBox<City> cobCity;
    @FXML
    private ComboBox<String> cobLevel;
    @FXML
    private RadioButton rdoAssigned;
    @FXML
    private RadioButton rdoUnassigned;
    @FXML
    private ToggleGroup AssignGroup;


    private HashMap<String, Province> provinceMap = new HashMap<>();
    private HashMap<String, City> cityMap = new HashMap<>();


    private ObservableList<RowAqiData> tableList = FXCollections.observableArrayList();

    @FXML
    private DatePicker datePicker;

    @FXML
    public void initialize(){

        // 初始化分配状态单选按钮组
        AssignGroup = new ToggleGroup();
        rdoAssigned.setToggleGroup(AssignGroup);
        rdoUnassigned.setToggleGroup(AssignGroup);
        rdoAssigned.setSelected(true);
        //日期控件使用
        //设置默认值为当前系统时间
        datePicker.setValue(LocalDate.now());

        //设置省、市
        // 设置ComboBox显示方式
        setupComboBoxDisplay();
        // 设置省份选择监听器
        setupProvinceSelectionListener();
        // 初始化污染等级下拉框
        initLevelComboBox();

        // 初始化列绑定
        initializeTableColumns();
        // 加载数据
        loadDataToTable();
    }

    private void setupComboBoxDisplay() {
        // 设置省份ComboBox显示
        cobProvince.setConverter(new StringConverter<Province>() {
            @Override
            public String toString(Province province) {
                return province == null ? "" : province.getName();
            }

            @Override
            public Province fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 设置城市ComboBox显示
        cobCity.setConverter(new StringConverter<City>() {
            @Override
            public String toString(City city) {
                return city == null ? "" : city.getName();
            }

            @Override
            public City fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 填充省份数据
        provinceMap = MyUtils.readFileToHashMap("group/data/location_hashmap.dat");
        ObservableList<Province> provinces = FXCollections.observableArrayList(provinceMap.values());
        cobProvince.setItems(provinces);
    }

    private void setupProvinceSelectionListener() {
        cobProvince.getSelectionModel().selectedItemProperty().addListener((obs, oldProvince, newProvince) -> {
            cobCity.getItems().clear();

            if (newProvince != null) {
                // 获取选中省份的城市列表
                ObservableList<City> cities = FXCollections.observableArrayList(
                        newProvince.getCities().values()
                );
                cobCity.setItems(cities);
            }
        });
    }

    private void initLevelComboBox() {
        // 确保 cobLevel 已经通过 @FXML 注入
        if (cobLevel != null) {
            ObservableList<String> levels = FXCollections.observableArrayList(
                    "优", "良", "轻度污染", "中度污染", "重度污染", "严重污染");
            cobLevel.setItems(levels);

            // 可选：设置默认选中项
            // cobLevel.getSelectionModel().selectFirst();
        } else {
            System.err.println("Error: cobLevel ComboBox is not initialized!");
        }
    }


    //清除按钮
    public void clear(ActionEvent actionEvent) {
        cobProvince.getSelectionModel().clearSelection();
        cobCity.getSelectionModel().clearSelection();
        cobLevel.getSelectionModel().clearSelection();
        datePicker.setValue(null);

        // 重置分配状态单选按钮为默认值
        rdoAssigned.setSelected(true);

        // 重新加载原始数据到表格
        loadDataToTable();
    }

    //查找按钮
    public void check(ActionEvent actionEvent) {
        // 获取筛选条件
        Province selectedProvince = cobProvince.getSelectionModel().getSelectedItem();
        City selectedCity = cobCity.getSelectionModel().getSelectedItem();
        String selectedLevel = cobLevel.getSelectionModel().getSelectedItem();
        LocalDate selectedDate = datePicker.getValue();
        boolean filterAssigned = rdoAssigned.isSelected();
        boolean filterUnassigned = rdoUnassigned.isSelected();

        ArrayList<RowAqiData> CheckList = new ArrayList<>();
        // 获取总行数
        int rowCount = tableView.getItems().size();

        // 通过索引遍历
        for (int i = 0; i < rowCount; i++) {
            RowAqiData rowData = tableView.getItems().get(i);
            Boolean isAssigned = isDataAssigned(String.valueOf(i+1));
            Boolean checkProvince = (selectedProvince == null || rowData.getLocation().getProvince().getName().equals(selectedProvince.getName()));
            Boolean checkCity = (selectedCity == null || rowData.getLocation().getCity().getName().equals(selectedCity.getName()));
            Boolean checkLevel = (selectedLevel == null || switchAqiLevel(rowData.getAqiLevel()).equals(selectedLevel));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            Boolean checkDate = (selectedDate == null || rowData.getTime().format(formatter).equals(selectedDate.format(formatter)));
            if(checkProvince && checkCity && checkLevel && checkDate && ((filterAssigned && isAssigned) || (filterUnassigned && !isAssigned)))
            {
                CheckList.add(rowData);
            }
        }

        ObservableList<RowAqiData> tableData = FXCollections.observableArrayList(CheckList);

        tableView.setItems(tableData);

    }

    // 初始化TableView列
    private void initializeTableColumns() {
        // 编号列（假设使用HashMap的key作为编号）
        colId.setCellValueFactory(cellData -> {
            int rowNumber = cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1;
            return new SimpleStringProperty(String.valueOf(rowNumber));
        });

        colName.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getUser().getUsername()));

        colProvince.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getLocation().getProvince().getName()));

        colCity.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getLocation().getCity().getName()));

        colLevel.setCellValueFactory(cellData ->
                new SimpleStringProperty(switchAqiLevel(cellData.getValue().getAqiLevel())));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        colDate.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getTime().format(formatter)));

        colTime.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getTime().toString())); // 或者格式化时间

        //详情按钮
        colDetail.setCellFactory(cols->new TableCell<>(){
            private Button btn = new Button("详情");
            {
                btn.setOnAction(e->{
                    RowAqiData user = getTableView().getItems().get(getIndex());
                    // 获取当前行索引
                    int rowIndex = getIndex();
                    ThePublic_DetialController.NEPMsetSelectedRowAqiData(user,rowIndex + 1);
                    MyUtils.navigateToView(e,"group/nepm/publicSuperviseDataManagement/view/PublicSupervise_Detail.fxml");
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });

        //指派按钮
        colAssign.setCellFactory(cols->new TableCell<>(){
            private Button btn = new Button("指派");
            {
                btn.setOnAction(e->{
                    RowAqiData user = getTableView().getItems().get(getIndex());
                    // 获取当前行索引
                    int rowIndex = getIndex();
                    ThePublic_AssignController.NEPMsetSelectedRowAqiData(user,rowIndex + 1);
                    //判断任务是否已经被分配
                    HashMap<String, AssignData> assignDataMap = MyUtils.readFileToHashMap("group/data/publicSupervise_assign_data_hashmap.dat");
                    if(assignDataMap == null){
                        assignDataMap = new HashMap<>();
                    }
                    String ID = String.valueOf(rowIndex + 1);
                    if(isDataAssigned(ID)){
                        MyUtils.showAlert("分配失败","该数据已分配", "分配失败", Alert.AlertType.ERROR);
                        return;
                    }
                    MyUtils.navigateToView(e,"group/nepm/publicSuperviseDataManagement/view/PublicSupervise_Assign.fxml");
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });

    }
    // 加载数据到TableView
    private void loadDataToTable() {
        ArrayList<RowAqiData> NEPSuserList = MyUtils.readFileToArrayList("group/data/row_aqi_data_arraylist.dat");

        ObservableList<RowAqiData> tableData = FXCollections.observableArrayList(NEPSuserList);

        tableView.setItems(tableData);
    }

    public void adminOut(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/common/view/NEPMLoginView.fxml");
    }
    public void toPublicSuperviseDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");
    }
    public void toConfirmAqiDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/ConfirmAqiDataList.fxml");
    }
    public void toProvinceStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/provinceStatistic.fxml");
    }
    public void toAqiDistributionStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiDistributionStatistic.fxml");
    }
    public void toAqiTendencyStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiTendencyStatistic.fxml");
    }
    public void toOtherDataStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/otherDataStatistic.fxml");
    }

    private boolean isDataAssigned(String id) {
        //判断任务是否已经被分配
        HashMap<String, AssignData> assignDataMap = MyUtils.readFileToHashMap("group/data/publicSupervise_assign_data_hashmap.dat");
        if (assignDataMap == null) {
            assignDataMap = new HashMap<>();
            return false;
        }

        if (assignDataMap.containsKey(id)) {
            return true;
        }else {
            return false;
        }
    }

    //将level转换成对应的AQI等级
    private String switchAqiLevel(RowAqiLevel level) {
        int key = level.ordinal()+1;
        String AQILevel = "";
        switch (key){
            case 1:{
                AQILevel = "优";
                break;
            }
            case 2:{
                AQILevel = "良";
                break;
            }
            case 3:{
                AQILevel = "轻度污染";
                break;
            }
            case 4:{
                AQILevel = "中度污染";
                break;
            }
            case 5:{
                AQILevel = "重度污染";
                break;
            }
            case 6:{
                AQILevel = "严重污染";
                break;
            }

        }
        return AQILevel;

    }


}
